package org.yourorghere;

import com.sun.opengl.util.Animator;
import com.sun.opengl.util.BufferUtil;
import java.awt.Frame;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.nio.IntBuffer;
import java.util.Locale;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.glu.GLU;



/**
 * OGLCubeSelect.java <BR>
 * author: Brian Paul (converted to Java by Ron Cemer and Sven Goethel) <P>
 *
 * This version is equal to Brian Paul's version 1.2 1999/10/21
 */
public class OGLCubeSelect implements GLEventListener, KeyListener, MouseListener, MouseWheelListener {

    private final static int RED = 0;
    private final static int BLUE = 1;
    private final static int GREEN = 2;

    private static final int BUFSIZE = 10;
    private Point pickpoint= new Point();
    private GLU glu;
    private boolean isMouseClicked = false;

    private float rx=0.0f;
    
    public static void main(String[] args) {
        Frame frame = new Frame("Simple JOGL Application");
        GLCanvas canvas = new GLCanvas();

        canvas.addGLEventListener(new OGLCubeSelect());
        frame.add(canvas);
        frame.setSize(640, 480);

        final Animator animator = new Animator(canvas);
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                // Run this on another thread than the AWT event queue to
                // make sure the call to Animator.stop() completes before
                // exiting
                new Thread(new Runnable() {

                    public void run() {
                        animator.stop();
                        System.exit(0);
                    }
                }).start();
            }
        });
        // Center frame
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        animator.start();
        
        canvas.requestFocusInWindow();

    }


    public void init(GLAutoDrawable drawable) {
        // Use debug pipeline
        // drawable.setGL(new DebugGL(drawable.getGL()));

        GL gl = drawable.getGL();
        System.err.println("INIT GL IS: " + gl.getClass().getName());

        // Enable VSync
        gl.setSwapInterval(1);

        // Setup the drawing area and shading mode
        gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        gl.glShadeModel(GL.GL_SMOOTH); // try setting this to GL_FLAT and see what happens.

        drawable.addKeyListener(this);
        drawable.addMouseListener(this);
        drawable.addMouseWheelListener(this);
    }

    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
        GL gl = drawable.getGL();
        glu = new GLU();

        if (height <= 0) { // avoid a divide by zero error!
        
            height = 1;
        }
        final float h = (float) width / (float) height;
        gl.glViewport(0, 0, width, height);
        gl.glMatrixMode(GL.GL_PROJECTION);
        gl.glLoadIdentity();
        glu.gluPerspective(45.0f, h, 1.0, 20.0);
        gl.glMatrixMode(GL.GL_MODELVIEW);
        gl.glLoadIdentity();
    }

    public void display(GLAutoDrawable drawable) {
        GL gl = drawable.getGL();

        // Clear the drawing area
        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
        // Reset the current matrix to the "identity"
        gl.glLoadIdentity();
        // Move the "drawing cursor" around


        if(isMouseClicked)
        {
            selectObjectsScene(gl);
            isMouseClicked = false;
        }
        drawScene(gl, GL.GL_RENDER);

        
    }

    public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
    }

    public void drawCube(GL gl, float a, int mode, int name, int color) {
        if(mode == GL.GL_SELECT)
            gl.glLoadName(name);
        gl.glBegin(GL.GL_QUADS);
        switch(color)
        {
            case RED:   gl.glColor3f(1.0f, 0.0f, 0.0f);
                break;
            case BLUE:  gl.glColor3f(0.0f, 0.0f, 1.0f);
                break;
            case GREEN: gl.glColor3f(0.0f, 1.0f, 0.0f);
                break;
        }
        gl.glVertex3f(-a, -a, a);//1
        gl.glVertex3f(a, -a, a);//2
        gl.glVertex3f(a, a, a);//7
        gl.glVertex3f(-a, a, a);//8


//        gl.glColor3f(0.0f, 0.0f, 1.0f);
        gl.glVertex3f(a, a, a);//7
        gl.glVertex3f(-a, a, a);//8
        gl.glVertex3f(-a, a, -a);//5
        gl.glVertex3f(a, a, -a);//6

//        gl.glColor3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(-a, a, -a);//5
        gl.glVertex3f(a, a, -a);//6
        gl.glVertex3f(a, -a, -a);//3
        gl.glVertex3f(-a, -a, -a);//4

//        gl.glColor3f(0.0f, 0.0f, 1.0f);
        gl.glVertex3f(a, -a, -a);//3
        gl.glVertex3f(-a, -a, -a);//4
        gl.glVertex3f(-a, -a, a);//1
        gl.glVertex3f(a, -a, a);//2

//        gl.glColor3f(1.0f, 0.0f, 0.0f);
        gl.glVertex3f(a, -a, a);//2
        gl.glVertex3f(a, a, a);//7
        gl.glVertex3f(a, a, -a);//6
        gl.glVertex3f(a, -a, -a);//3

//        gl.glColor3f(0.0f, 1.0f, 0.0f);
        gl.glVertex3f(-a, -a, a);//1
        gl.glVertex3f(-a, a, a);//8
        gl.glVertex3f(-a, a, -a);//5
        gl.glVertex3f(-a, -a, -a);//4

        gl.glEnd();
    }

    public void drawTetrahedron(GL gl, float a, int mode, int id) {

        if(mode == GL.GL_SELECT)
            gl.glLoadName(id);

        gl.glBegin(GL.GL_TRIANGLES);
        gl.glColor3f(1.0f, 0.0f, 0.0f);

        gl.glVertex3f(a, a, a);//1
        gl.glVertex3f(-a, -a, a);//2
        gl.glVertex3f(-a, a, -a);//3

        gl.glVertex3f(a, a, a);//1
        gl.glVertex3f(-a, a, -a);//3
        gl.glVertex3f(a, -a, -a);//4

        gl.glVertex3f(a, a, a);//1
        gl.glVertex3f(a, -a, -a);//4
        gl.glVertex3f(-a, -a, a);//2

        gl.glVertex3f(a, -a, -a);//4
        gl.glVertex3f(-a, -a, a);//2
        gl.glVertex3f(-a, a, -a);//3

        gl.glEnd();

    }

    private void drawScene(GL gl, int mode) {

        gl.glPushMatrix();
        gl.glTranslatef(0.0f, 0.0f, -5.0f);
        gl.glRotatef(rx, 1.0f, 0.0f, 0.0f);

        gl.glPushMatrix();
        drawCube(gl, 1.0f, mode, 1, GREEN);
        gl.glPopMatrix();

        gl.glPushMatrix();
        gl.glTranslatef(1.0f, 1.0f, 1.0f);
        drawTetrahedron(gl, 0.02f, mode, 2);
        gl.glPopMatrix();

        gl.glPushMatrix();
        gl.glTranslatef(-1.0f, -1.0f, 1.0f);
        drawTetrahedron(gl, 0.02f, mode, 3);
        gl.glPopMatrix();

        gl.glPushMatrix();
        gl.glTranslatef(1.0f, -1.0f, -1.0f);
        drawTetrahedron(gl, 0.02f, mode, 4);
        gl.glPopMatrix();

        gl.glPopMatrix();
        gl.glFlush();
    }

    private void selectObjectsScene(GL gl) {

        int selectBuf[] = new int[BUFSIZE];
        IntBuffer selectBuffer = BufferUtil.newIntBuffer(BUFSIZE);
        int hits;
        int viewport[] = new int[4];

        gl.glGetIntegerv(GL.GL_VIEWPORT, viewport, 0);

        gl.glSelectBuffer(BUFSIZE, selectBuffer);
        gl.glRenderMode(GL.GL_SELECT);

        gl.glInitNames();
        gl.glPushName(-1);

        gl.glMatrixMode(GL.GL_PROJECTION);

        gl.glPushMatrix();
        gl.glLoadIdentity();

        glu.gluPickMatrix((double) pickpoint.x,
                          (double) (viewport[3] - pickpoint.y),
                          2,
                          2,
                          viewport,
                          0);


        //glu.gluPerspective(90, 1  , 0.0001,  1000.0);
        glu.gluPerspective(45.0f, 1.4, 1.0, 20.0);
        //gl.glOrtho(0, 3, 0, 3, -0.5, 2.5);


        drawScene(gl, GL.GL_SELECT);

        gl.glPopMatrix();
        gl.glFlush();

        hits = gl.glRenderMode(GL.GL_RENDER);
        selectBuffer.get(selectBuf);
        processHits(hits, selectBuf);
        gl.glMatrixMode(GL.GL_MODELVIEW);
    }

    private void processHits(int hits, int buffer[]) {

        System.out.println("hits = " + hits);

        if(hits > 0){
            int len = buffer.length;
            System.out.print("Buffer Content [ ");
            for(int j=0; j<len; j++)
            {
                System.out.print(buffer[j] + ", ");
            }
            System.out.print("] : End of Buffer Content.\n");

            float f = 2.3455f;
            System.out.printf(Locale.getDefault(),"%f",f);
        }
    }

    public void keyTyped(KeyEvent e) {

    }

    public void keyPressed(KeyEvent e) {

    }

    public void keyReleased(KeyEvent e) {

    }

    public void mouseClicked(MouseEvent e) {

    }

    public void mousePressed(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1) //
        {
            pickpoint = e.getPoint();
            isMouseClicked = true;
        }
    }

    public void mouseReleased(MouseEvent e) {

    }

    public void mouseEntered(MouseEvent e) {

    }

    public void mouseExited(MouseEvent e) {

    }

    public void mouseWheelMoved(MouseWheelEvent e) {

        rx +=  ((float) e.getWheelRotation()) ;



    }
}

